//index.js
//获取应用实例
import '../../api/public'
import '../../api/index'
import { getcarlist, carDetail, getMemberPrice, saveOrder, getUserInfo, getoldorder} from '../../api/index'
const app = getApp()
import { pay } from "../../api/public"

Page({
  data: {
    animationData:{},
    carlistdata:[],
    cardetaildata:{},
    calendarshow:false,
    namevalue:'aaaaaa',
    overlayshow:false,
    swiper_father_index:0,
    windotop:0,
    initHeight:0,
    statusBarHeight:0,
    blokindex:0,
    starty:0,  //开始位置

    // 请求车类型
    car_index:0,
    //用车地点
    useLocation:'',
    //还车地点
    stillLocation:'',
    //用车时间
    date: {
      start: "",
      end: "",
      day:""
    },
    name:"",
    phone:"",
    //支付弹框
    payFlag:false,
    //根据天数计算的总价格
    allPrice:'',
    dateint:[],
    orderId:'',
    orderDetail: {
      orderNum: '',
      showMoney: ''
    },
    userInfo:'',
    islocationdata:false,
  },
  islocation(){
    this.setData({
      islocationdata:true
    })
  },
  colslocpopop(){
    this.setData({
      islocationdata:false
    })
  },
 animat(){
  wx.switchTab({
    url: '/pages/onlineGarage/onlineGarage',
  })
  // this.setData({
  //   swiper_father_index:1,
  // })
 },
 service(){
  console.log('23123')
  wx.makePhoneCall({
    phoneNumber: '400-180-0001'
  })
},
 close(e){
      let that = this;
      that.animation.bottom('-1000rpx').step()
      wx.showTabBar({
        animation:false
      })
      this.setData({
        animationData:this.animation.export()
      })
      setTimeout(()=>{
        that.setData({
          overlayshow:false
        })
      },300)
 },
  //日历组件部分
  oncalendarClose(e){
    this.setData({
      calendarshow:false
     })
  },
 calendarfn(e){
   this.setData({
    calendarshow:true
   })
 },
  place(e){
    let that = this;
    let inid = e.currentTarget.dataset.item.id;
    carDetail({
      data:{
        id:inid,
      }
    })
    .then((res)=>{
      this.setData({
        cardetaildata:res.data.car
      })
      this.getMemberMoney()
    })
    // day = new Date(endTime - startTime).getDate() - 1
    this.setData({
      overlayshow:true,
    })
    setTimeout(()=>{
      that.animation.bottom('0').step()
      that.setData({
        animationData:this.animation.export()
      })
      wx.hideTabBar({
        animation:true
      })
    },50)
  },
  onClickHide(){
    this.setData({
      overlayshow:false
    })
  },
 bloktab(e){
   let index = e.currentTarget.dataset.index;
   this.setData({
    blokindex:index
   })
 },
 swiperchage(e){
   let index = e.detail.current;
   this.setData
   index == 0 ? this.dateinitFn(3) : this.dateinitFn(1)
   this.setData({
    blokindex:index
   })
 },
 swiper_father_change(e){},
  onLoad: function () {                       
  },
  //日历事件
  onConfirm(event) {
    
    if (this.data.blokindex == 0) {
      const [start, end] = event.detail;
      const startTime = new Date(start).getTime();
      const endTime = new Date(end).getTime();
      this.setData({
        calendarshow: false,
        date: {
          start: this.formatDate(start),
          end: this.formatDate(end),
          day: new Date(endTime - startTime).getDate()-1
        },
        useStartTime: startTime,
        useEndTime: endTime,
        
      });
      this.getMemberMoney()
      // this.dayChange();
    } else {
      this.setData({
        calendarshow: false,
        date: {
          start: this.formatDate(event.detail),
          end: this.formatDate(event.detail),
          day: 1
        },
        useStartTime: new Date(event.detail).getTime(),
        useEndTime: new Date(event.detail).getTime(),
        day: 1
      });
      // this.dayChange();
    }
  },
  //提交订单
  apply() {
    if (!this.data.name) return wx.showToast({
      title: '姓名为必填',
      icon: 'none'
    })
    if (this.data.name.indexOf(' ') != -1) return wx.showToast({
      title: '姓名中不能输入空格',
      icon: 'none'
    })
    if (this.data.phone.length != 11) return wx.showToast({
      title: '请填写正确的手机号',
      icon: 'none'
    })
    getUserInfo({})
    .then((res)=>{
      if(res.code == 203){
        wx.showModal({
          title: '提示',
          content: '您还未登录，是否进行登录',
          success(res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/login/login',
              })
              wx.hideLoading()
            } else if (res.cancel) {
             wx.hideLoading()
            }
          }
        })
        return 
      }else{
        saveOrder({
          data: {
            carId: this.data.cardetaildata.id + '',
            useDays: this.data.date.day + '',
            firstName: this.data.name,
            orUsername: this.data.phone,
            orMoney: this.data.allPrice*100 + '',
            // label: this.data.remarks,
            sentCarPlace: this.data.useLocation,
            useCarTime: this.data.dateint[0],
            getCarTime: this.data.dateint[1]
          }
        })
        .then(e => {
          this.setData({
            payFlag:true
          })
          this.data.orderId = e.data.orderId;
          this.judgeMember();
        })
  }
})
  },
  getMemberMoney() {
    wx.showLoading({
      title: '加载中...',
    })
    getMemberPrice({
      data: {
        carId: this.data.cardetaildata.id,
        days: this.data.date.day
      }
    }).then(e => {
      this.setData({
        discountPrice: e.data.discountMoney,
        allPrice: e.data.discountLater
      })
      wx.hideLoading();
    })
  },
  // dayChange() {
  //   if (isNaN(Number(this.data.day)) || this.data.day <= 0) this.setData({
  //     day: 1
  //   });
  //   // if (this.data.userInfo.memberLevel == 0) {
  //   //   this.setData({
  //   //     allPrice: (this.data.day * this.data.carData.price).toFixed(2)
  //   //   })
  //   // } else {
  //     this.getMemberMoney()
  //   // }
  // },
  //初始化时间
  dateinitFn(dayNum){
    let daynum = dayNum || 1;
    const date = new Date();
    //日历默认选中天数
    let year=date.getFullYear();
    let month=date.getMonth();
    let today=date.getDate();
    let stat=  new Date(year,month,today).getTime();
    let en =  new Date(year,month,today+daynum).getTime();
    let d = [stat,en]
    console.log(d)
    //显示文案
    let stattxt = `${date.getMonth() + 1}月${date.getDate()}日`;
    let entxt = `${date.getMonth()+1}月${date.getDate() + daynum}日`;
    this.setData({
      date: {
        start: stattxt,
        end: entxt,
        day: daynum,
      },
      dateint:d
    });
  },
  formatDate(date) {
    date = new Date(date);
    return `${date.getMonth() + 1}月${date.getDate()}日`;
  },
  //跳转地图
  goMap(e) {
    let index = e.currentTarget.dataset.index;
    wx.chooseLocation({
      location,
      success:(res=>{
        if(index == 0){
          console.log(res,'asdas')
          this.setData({
            useLocation:res.address,
            stillLocation:res.address
          })
        }else{
          this.setData({
            stillLocation:res.address
          })
        }
      })
    })
    // const key = 'R2IBZ-EDB32-SULUG-CD63A-PCM45-MYBYC'; //使用在腾讯位置服务申请的key
    const location = JSON.stringify({
      latitude: 39.89631551,
      longitude: 116.323459711
    });
    // const category = '定位服务';
    // wx.navigateTo({
    //   url: 'plugin://chooseLocation/index?key=' + key + '&referer=' + referer + '&location=' + location + '&category=' + category
    // });
  },
  //请求部分---------------------
  carlist(index){
    let resdata = []
    getcarlist({
      data:{
        useNature:0
      }
    })
    .then((res)=>{
      resdata.push(res.data.carList)
      getcarlist({
        data:{
          useNature:1
        }
      })
      .then((res)=>{
        resdata.push(res.data.carList)
        this.setData({
          carlistdata:resdata
        })
      })
    })
  },
  judgeMember() {
    wx.showLoading({
      title: '加载中...',
    })
    getUserInfo({}).then(e => {
      if(e.code == 200 ){
        this.setData({
          userInfo: e.data.userInfo,
          payFlag: false,
        })
      }
      
      if (this.data.userInfo.memberLevel == 0) {
        pay(1,this.data.orderId,true);
      } else {
        this.setData({
          payFlag: true,
          orderDetail: {
            orderNum: this.data.orderId,
            showMoney: this.data.allPrice
          }
        })
        wx.hideLoading()
      }
    })
  },
  onReady:function(){
    // getoldorder({})
    // .then((res)=>{
    //   this.setData({
    //     useLocation:res.data.sentCarPlace,
    //     stillLocation:res.data.sentCarPlace,
    //     phone:res.data.orUsername
    //   })
    // })
  },
  onShow:function(){
    
    let BarHeight = wx.getSystemInfoSync().statusBarHeight;
    //右上角胶囊高度
    let button = wx.getMenuButtonBoundingClientRect().height;
    //动画
    this.animation = wx.createAnimation({
      duration:300
    })
    this.setData({
      statusBarHeight:BarHeight,
      initHeight:wx.getSystemInfoSync().windowHeight,
    })
    //用户信息
    // getUserInfo({}).then(e => {
    //   this.setData({
    //     userInfo: e.data.userInfo
    //   })
    //   if (this.data.userInfo.memberLevel == 0) {
    //     wx.hideLoading()
    //   } else {
    //     // this.getMemberMoney();
    //   }
    // })
    //初始化日期
    // if(this.data.date.day < 1){
    //   this.dateinitFn(3)
    // }
    console.log(this.data.date,'dasdededede')
    // this.carlist();
  },
  imgLoadEnd: function (e) {
    let statusBarHeight = wx.getSystemInfo().statusBarHeight;
    this.setData({
      statusBarHeight:statusBarHeight
    })
  },
  onPullDownRefresh: function () {
   
  },
  onShareAppMessage: function () {
    return {
      title: '信用免押金，租车更放心',
      path:`/pages/index/index`,
      imageUrl:'https://api.qihaochuxing.com/mini/images/4f5965758d9dde018485c705b4226a1a'
    }
},
rt(){
  return
}
})
